package com.ygqh.baby.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.crazycake.shiro.SerializeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.model.TemplateMessageInfo;
import com.foxinmy.weixin4j.util.NameValue;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.WxMessageType;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgUserService;

@Service
public class BaseWxMpMessageService {
	private final Logger logger = Logger.getLogger(BaseWxMpMessageService.class);
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private RedisDao redisDao;
	@Value("${micro.msg.appId}")
	protected String appId;

	protected Boolean canSend(YgUser user) {

		if (user == null || StringUtil.isBlank(user.getOpenId()) || !user.getIsSubscribe()) {
			return false;
		}
		return true;
	}

	protected Boolean canSend(Long userId) {

		YgUser user = ygUserService.findUserById(userId);

		return this.canSend(user);
	}

	protected Boolean canSend(String openId) {

		YgUser user = ygUserService.findByOpenId(openId);

		return this.canSend(user);
	}

	public Message sendTemplateMessage(TemplateMessage tplMessage) {
		TmplApi tmplApi = new TmplApi(wxMpAuthorityService.findTokenHolder());
		JsonResult sendResult = null;
		try {
			sendResult = tmplApi.sendTmplMessage(tplMessage);
		} catch (WeixinException e) {
			logger.error("发送微信模板消息失败；openId=【" + tplMessage.getToUser() + "】【" + tplMessage.getHead() + "】"
					+ e.getMessage());
			e.printStackTrace();
			return Message.error(e.getMessage(), null);
		}
		return Message.success(sendResult.getText(), null);
	}

	public String getWxMsgTempId(WxMessageType messageType) {

		String key = String.format("wx_tempid_%s", appId + messageType.name());
		String msgTmpId = (String) SerializeUtils.deserialize(redisDao.get(key.getBytes()));
		if (StringUtil.isEmpty(msgTmpId)) {
			List<TemplateMessageInfo> list = getTemplateMessageList();
			for (TemplateMessageInfo msg : list) {
				if (messageType.getTitle().equals(msg.getTitle())) {
					redisDao.set(key.getBytes(), SerializeUtils.serialize(msg.getTemplateId()));
					return msg.getTemplateId();
				}
			}
		}
		return msgTmpId;
	}

	/**
	 * 获取模板消息列表
	 * 
	 * @Title: getTemplateMessageList
	 * @return 入参
	 * @return List<TemplateMessageInfo> 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年8月3日 下午7:09:33
	 * @version V1.0
	 */
	public List<TemplateMessageInfo> getTemplateMessageList() {
		List<TemplateMessageInfo> allTemplates = null;
		try {
			TmplApi tmplApi = new TmplApi(wxMpAuthorityService.findTokenHolder());
			allTemplates = tmplApi.getAllTemplates();
		} catch (WeixinException e) {
			allTemplates = new ArrayList<TemplateMessageInfo>();
			e.printStackTrace();
		}
		return allTemplates;
	}

	/**
	 * 发送模板消息 可设置字体颜色
	 * 
	 * @Title: sendTemplateMessage
	 * @param messageType
	 * @param openId
	 * @param url
	 * @param contentMap
	 *            map的key 微消息模板的key ; </br> NameValue(color,text) color 为空时
	 *            默认颜色为 #323232
	 * @return Message 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年8月3日 下午7:06:21
	 * @version V1.0
	 */
	public Message sendTemplateMessage(WxMessageType messageType, String openId, String url,
			Map<String, NameValue> contentMap) {
		String wxMsgTempId = this.getWxMsgTempId(messageType);
		TemplateMessage tplMessage = new TemplateMessage(openId, wxMsgTempId, "", url);
		for (Entry<String, NameValue> entry : contentMap.entrySet()) {
			String color = StringUtil.isBlank(entry.getValue().getName()) ? "#323232" : entry.getValue().getName();
			if (entry.getKey().equals("first")) {
				tplMessage.pushHead(color, entry.getValue().getValue());
			}
			tplMessage.pushItem(entry.getKey(), color, entry.getValue().getValue());
		}

		return this.sendTemplateMessage(tplMessage);
	}

	public Message sendTemplateMessage(WxMessageType messageType, YgUser user, String url,
			Map<String, NameValue> contentMap) {
		if (!canSend(user)) {
			return Message.error("该用户未绑定微信，或已取关", user.getId());
		}

		return this.sendTemplateMessage(messageType, user.getOpenId(), url, contentMap);
	}

	/**
	 * 只适用于模板的key 为keyword1 等等
	 * 
	 * @Title: sendTemplateMessage
	 * @param messageType
	 * @param head
	 * @param openId
	 * @param url
	 * @param keywords
	 *            这里需按照keyword顺序依次传参
	 * @return 入参
	 * @return Message 返回类型
	 * @author （guohao）
	 * @throws
	 * @date 2017年8月3日 下午7:01:41
	 * @version V1.0
	 */
	public Message sendTemplateMessage(WxMessageType messageType, String head, String remark, String openId,
			String url, String... keyword) {
		String wxMsgTempId = this.getWxMsgTempId(messageType);
		TemplateMessage tplMessage = new TemplateMessage(openId, wxMsgTempId, head, url);
		tplMessage.pushHead("#323232", head);
		tplMessage.pushTail(remark);
		for (int i = 0; i < keyword.length; i++) {
			tplMessage.pushItem("keyword" + (i + 1), "#323232", keyword[i]);
		}
		return this.sendTemplateMessage(tplMessage);
	}

}
